<template>
  <drag-modal
    title="新增"
    :width="450"
    :visible="visible"
    :destroyOnClose="true"
    :confirmLoading="submitLoading"
    :maskClosable="false"
    @ok="ok"
    @cancel="cancel"
  >
    <a-spin :spinning="loading">
      <a-form-model :model="form" ref="form" :rules="validatorRules" :label-col="{span: 5}" :wrapperCol="{span: 16, offset: 1}">
        <div class="fold">
          <a-form-model-item
            label="类型"
            prop="type"
          >
            <a-select allowClear v-model="form.type" @change="onTypeChange" :getPopupContainer="(triggerNode)=>{ return triggerNode.parentNode}">
              <a-select-option v-for="item in dict.type" :key="item.key" :value="item.value">{{item.title}}</a-select-option>
            </a-select>
          </a-form-model-item>
          <a-form-model-item
            v-if="form.type != 0"
            label="上级区域"
            prop="parentId"
          >
            <a-select show-search :filter-option="filterOption" allowClear v-model="form.parentId" :getPopupContainer="(triggerNode)=>{ return triggerNode.parentNode}" @search="onCitySearch" @popupScroll="onCityPopupScroll">
              <a-select-option v-for="item in cityDataList" :key="item.key" :value="item.value">{{item.title}}</a-select-option>
            </a-select>
          </a-form-model-item>
          <a-form-model-item
            label="名称"
            prop="name"
          >
            <a-input allowClear v-model="form.name" />
          </a-form-model-item>
          <a-form-model-item
            label="层级"
            prop="level"
          >
            <a-input allowClear v-model="form.level" @change="(e) => form.level = e.target.value.replace(/[^0-9]/g, '')" />
          </a-form-model-item>
          <a-form-model-item
            label="层级序列"
            prop="levelSqe"
          >
            <a-input allowClear v-model="form.levelSqe" />
          </a-form-model-item>
        </div>
      </a-form-model>
    </a-spin>
  </drag-modal>
</template>

<script>
import {regionService} from '@/services'

export default {
  name: 'AddModal',
  props: {
    visible: {
      type: Boolean,
      required: true
    }
  },
  data () {
    return {
      loading: false,
      submitLoading: false,
      cityTotalDataList: [],
      cityDataList: [],
      cityPageSize: 50,
      cityPage: 1,
      citySearchValue: '',
      form: {
        type: undefined,
        level: undefined,
        levelSqe: undefined,
        parentId: undefined,
        name: undefined
      },
      validatorRules: {
        type: [
          { required: true, message: '请选择类型', trigger: 'change' }
        ],
        name: [
          { required: true, message: '请输入名称', trigger: 'blur' }
        ],
        level: [
          { required: true, message: '请输入层级', trigger: 'blur' }
        ],
        levelSqe: [
          { required: true, message: '请输入层级序列', trigger: 'blur' }
        ],
        parentId: [
          { required: true, message: '请选择上级区域', trigger: 'change' }
        ]
      },
      dict: {
        type: []
      }
    }
  },
  methods: {
    cancel() {
      this.$emit('cancel')
    },
    ok() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.submitLoading = true
          regionService.add(JSON.stringify(this.form)).then(res => {
            const result = res.data
            if (result.code === 200) {
              this.$emit('ok')
              this.$message.success(result.msg)
            }
          }).finally(this.submitLoading = false)
        }
      })
    },
    onTypeChange(val) {
      this.form.parentId = undefined
      this.queryParentAction(val)
    },
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text.indexOf(input) >= 0
      )
    },
    onCitySearch(input) {
      this.citySearchValue = input
      if (!input) {
        this.queryParentAction()
      } else {
        this.cityDataList = []
        this.cityPage = 1
        let newCityData = []
        this.cityTotalDataList.forEach((item, index) => {
          if (item.title.indexOf(input) >= 0) {
            newCityData.push(item)
          }
        })
        this.cityDataList = [...this.cityDataList, ...newCityData.slice(0, this.cityPageSize)]
      }
    },
    onCityPopupScroll(e) {
      const { scrollHeight, scrollTop, clientHeight } = e.target
      // 下拉框不下拉的时候
      if (scrollHeight === 0 && clientHeight === 0) {
        this.cityPage = 1
      } else {
        // 当下拉框滚动条到达底部的时候
        if (scrollHeight - scrollTop === clientHeight) {
          this.cityPage += 1
          // 获取当前页码
          let cityPage = this.cityPage
          let newCityData = []
          // 得到需要开始拼接的数据下标
          let cursorStart = (cityPage - 1) * this.cityPageSize
          // 得到需要结束拼接的数据下标
          let cursorEnd = cityPage * this.cityPageSize
          // 判断是否有搜索
          if (this.citySearchValue) {
            let temp = []
            this.cityTotalDataList.forEach((item, index) => {
              if (item.title.indexOf(this.citySearchValue) >= 0) {
                temp.push(item)
              }
            })
            temp.forEach((item, index) => {
              if (index >= cursorStart && index < cursorEnd) {
                newCityData.push(item)
              }
            })
          } else {
            this.cityTotalDataList.forEach((item, index) => {
              if (index >= cursorStart && index < cursorEnd) {
                newCityData.push(item)
              }
            })
          }
           // 将新增的数据赋值到要显示的数组中
          this.cityDataList = [...this.cityDataList, ...newCityData]
        }
      }
    },
    queryParentAction(val) {
      this.loading = true
      let params = {
        type: val - 1
      }
      regionService.queryParentList(JSON.stringify(params)).then(res => {
        const result = res.data
        if (result.code === 200) {
          let tempCityDataList = result.data
          if (tempCityDataList && tempCityDataList.length > 0) {
            this.cityTotalDataList = tempCityDataList
            this.cityDataList = tempCityDataList.slice(0, this.cityPageSize)
          }
        }
      }).finally(this.loading = false)
    }
  },
  mounted() {
    this.getDict(JSON.stringify({code: 'SYS_REGION_TYPE'})).then(res => this.dict.type = res.data.data)
  }
}
</script>
